package com.aabte.weather.weatherbasic.weather;


import com.aabte.weather.weatherbasic.weather.dto.WeatherResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Slf4j
@Service
public class WeatherDataServiceImpl implements WeatherDataService {

    private static final String WEATHER_API = "http://wthrcdn.etouch.cn/weather_mini";

    @Resource
    private RestTemplate restTemplate;

    @Override
    public WeatherResponse getDataByCityId(String cityId) {
        String uri = WEATHER_API + "?citykey=" + cityId;
        return doGetWeatherData(uri);
    }

    @Override
    public WeatherResponse getDataByCityName(String cityName) {
        String uri = WEATHER_API + "?city=" + cityName;
        return doGetWeatherData(uri);
    }

    private WeatherResponse doGetWeatherData(String uri) {
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(uri, String.class);
        if (responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
            return null;
        }
        String responseBody = responseEntity.getBody();
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(responseBody, WeatherResponse.class);
        } catch (JsonProcessingException e) {
            log.error("deserialization failed. uri: {}", uri, e);
        }
        return null;
    }
}
